package 并发编程19.实际应用;

import java.util.concurrent.Semaphore;

/**
 * @author idea
 * @data 2019/2/24
 */
class SemaphoreWorker implements Runnable {

    private String name;

    private Semaphore semaphore;

    public SemaphoreWorker(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        System.out.println("this is waiting for a permit!");
        try {
            //请求资源
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("acquired a permit!");
        //释放资源
        semaphore.release();
    }
}

class MyWorker implements Runnable {

    private Semaphore semaphore;

    public MyWorker(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            //尝试获取许可，如果获取失败则堵塞
            semaphore.acquire();
            System.out.println(semaphore.availablePermits());
            System.out.println("Executed!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Demo1 {


    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(0);
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new MyWorker(semaphore));
            t.start();
        }
        System.out.println("Action...go");
        semaphore.release(5);
        System.out.println("wait for permits off");
        //保证前5个信号量已经获取完毕了
        while (semaphore.availablePermits() != 0) {
            Thread.sleep(100L);
            System.out.println("-0---");
        }
        System.out.println("action ... go");
        semaphore.release(5);
    }
}
